package com.example.teesystem.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.teesystem.common.exception.CustomException;
import com.example.teesystem.common.utils.*;
import com.example.teesystem.entity.Issue;
import com.example.teesystem.entity.Mcff;
import com.example.teesystem.mapper.IssueMapper;
import com.example.teesystem.mapper.McffMapper;
import com.example.teesystem.service.McffService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author NieYaShi
 * @description 针对表【t_mcff】的数据库操作Service实现
 * @createDate 2022-08-02 13:41:24
 */
@Service
@AllArgsConstructor
public class McffServiceImpl extends ServiceImpl<McffMapper, Mcff>
        implements McffService{

    private final IssueMapper issueMapper;
    private final McffMapper mcffMapper;

    private static Map<Integer, List<String>> mcffMap = new HashMap<>();

    @Override
    public Response featureMCFF(int issueId, String fileName) {
        //避免前端传递图片全路径
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }

        List<String> fileNameList = mcffMap.get(issueId);
        if (fileNameList == null){
            fileNameList = new ArrayList<>();
        }

        if (!fileNameList.contains(fileName)){
            // 加入到缓存中
            fileNameList.add(fileName);
            mcffMap.put(issueId, fileNameList);

            try{
                Mcff result = getResult(issueId, fileName);
                return Response.ok(result);
            }catch (CustomException e){
                return Response.error(e.getMsg(), e.getCode());
            }
        }
        return Response.ok("数据处理中，请稍后");
    }

    @Override
    public Response zeroCrossing(int issueId, String fileName) {
        //避免前端传递图片全路径
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        String filePath = getFilePath(issueId, fileName);
        if(filePath.equals("")){
            throw new CustomException(ResultCode.FEATURE_ISSUE_ERROR);
        }

        Map<String, String> map = new HashMap<>();
        map.put("filepath", filePath);
        int start = TimeUtil.getSecondTimestamp();
        System.out.println(start);
        try {
            String result = HttpUtil.httpRequestByPost("http://127.0.0.1:5000/v1/feature/Zero_Crossing", JSONUtil.parse(map));
            int end = TimeUtil.getSecondTimestamp();
            JSON json = JSONUtil.parse(result);
            json = (JSON) json.getByPath("data");
            System.out.println(end - start);
            return Response.ok(json);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
    }

    @Override
    public Response melSpectrogram(int issueId, String fileName) {
        //避免前端传递图片全路径
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        String filePath = getFilePath(issueId, fileName);
        if(filePath.equals("")){
            throw new CustomException(ResultCode.FEATURE_ISSUE_ERROR);
        }
        Map<String, String> map = new HashMap<>();
        map.put("filepath", filePath);
        map.put("resolution","25");//25默认值
        int start = TimeUtil.getSecondTimestamp();
        System.out.println(start);
        try {
            String result = HttpUtil.httpRequestByPost("http://127.0.0.1:5000/v1/feature/Mel_Spectrogram", JSONUtil.parse(map));
            int end = TimeUtil.getSecondTimestamp();
            JSON json = JSONUtil.parse(result);
            json = (JSON) json.getByPath("data");
            System.out.println(end - start);
            return Response.ok(json);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
    }

    @Override
    public Response power(int issueId, String fileName) {
        //避免前端传递图片全路径
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        String filePath = getFilePath(issueId, fileName);
        if(filePath.equals("")){
            throw new CustomException(ResultCode.FEATURE_ISSUE_ERROR);
        }

        Map<String, String> map = new HashMap<>();
        map.put("filepath", filePath);
        map.put("file_nfft","2048");//2048默认值
        int start = TimeUtil.getSecondTimestamp();
        System.out.println(start);
        try {
            String result = HttpUtil.httpRequestByPost("http://127.0.0.1:5000/v1/feature/Power", JSONUtil.parse(map));
            int end = TimeUtil.getSecondTimestamp();
            JSON json = JSONUtil.parse(result);
            json = (JSON) json.getByPath("data");
            System.out.println(end - start);
            return Response.ok(json);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
    }

    @Override
    public Response onethree(int issueId, String fileName) {
        //避免前端传递图片全路径
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        String filePath = getFilePath(issueId, fileName);
        if(filePath.equals("")){
            throw new CustomException(ResultCode.FEATURE_ISSUE_ERROR);
        }

        Map<String, String> map = new HashMap<>();
        map.put("filepath", filePath);
        int start = TimeUtil.getSecondTimestamp();
        System.out.println(start);
        try {
            String result = HttpUtil.httpRequestByPost("http://127.0.0.1:5000/v1/feature/onethree", JSONUtil.parse(map));
            int end = TimeUtil.getSecondTimestamp();
            JSON json = JSONUtil.parse(result);
            json = (JSON) json.getByPath("data");
            System.out.println(end - start);
            return Response.ok(json);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
    }

    @Override
    public Response demon_amalysis(int issueId, String fileName) {
        //避免前端传递图片全路径
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        String filePath = getFilePath(issueId, fileName);
        if(filePath.equals("")){
            throw new CustomException(ResultCode.FEATURE_ISSUE_ERROR);
        }

        Map<String, String> map = new HashMap<>();
        map.put("filepath", filePath);
        int start = TimeUtil.getSecondTimestamp();
        System.out.println(start);
        try {
            String result = HttpUtil.httpRequestByPost("http://127.0.0.1:5000/v1/feature/demon_amalysis", JSONUtil.parse(map));
            int end = TimeUtil.getSecondTimestamp();
            JSON json = JSONUtil.parse(result);
            json = (JSON) json.getByPath("data");
            System.out.println(end - start);
            return Response.ok(json);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
    }

    @Override
    public Response demon_amalysis2(int issueId, String fileName) {
        //避免前端传递图片全路径
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        String filePath = getFilePath(issueId, fileName);
        if(filePath.equals("")){
            throw new CustomException(ResultCode.FEATURE_ISSUE_ERROR);
        }
        Map<String, String> map = new HashMap<>();
        map.put("filepath", filePath);
        int start = TimeUtil.getSecondTimestamp();
        System.out.println(start);
        try {
            String result = HttpUtil.httpRequestByPost("http://127.0.0.1:5000/v1/feature/demon_amalysis2", JSONUtil.parse(map));
            int end = TimeUtil.getSecondTimestamp();
            JSON json = JSONUtil.parse(result);
            json = (JSON) json.getByPath("data");
            System.out.println(end - start);
            return Response.ok(json);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
    }

    @Override
    public Response lofar_v1(int issueId, String fileName) {
        //避免前端传递图片全路径
        if (fileName.contains("/")) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        String filePath = getFilePath(issueId, fileName);
        if(filePath.equals("")){
            throw new CustomException(ResultCode.FEATURE_ISSUE_ERROR);
        }

        Map<String, String> map = new HashMap<>();
        map.put("filepath", filePath);
        int start = TimeUtil.getSecondTimestamp();
        System.out.println(start);
        try {
            String result = HttpUtil.httpRequestByPost("http://127.0.0.1:5000/v1/feature/lofar_v1", JSONUtil.parse(map));
            int end = TimeUtil.getSecondTimestamp();
            JSON json = JSONUtil.parse(result);
            json = (JSON) json.getByPath("data");
            System.out.println(end - start);
            return Response.ok(json);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Response.error(ResultCode.PARAMETER_ERROR);
        }
    }

    Mcff getResult(int issueId, String fileName){
        //         判断是否包含传入的文件
        String filePath = getFilePath(issueId, fileName);
        if(filePath.equals("")){
            throw new CustomException(ResultCode.FEATURE_ISSUE_ERROR);
        }

        Mcff mcff = mcffMapper.getMcffByIssueIdAndFilename(issueId, fileName);
        if (mcff != null){
            mcffMap.get(issueId).remove(fileName);
            mcff.setPictureUrl(FileUtil.FILE_PREFIX + mcff.getPictureUrl());
            return mcff;
        }
        else {
            Map<String, String> map = new HashMap<>();
            map.put("filepath", filePath);
//        int start = TimeUtil.getSecondTimestamp();
//        System.out.println(start);
            try {
                String result = HttpUtil.httpRequestByPost("http://127.0.0.1:5000/v1/feature/MCFF", JSONUtil.parse(map));
                JSON json = JSONUtil.parse(result);
                json = (JSON) json.getByPath("data");
                String pictureString = (String) json.getByPath("picIfo");
                Base64ToFile.Base64ToFile(pictureString, FileUtil.FILE_PATH+FileUtil.MCFF + issueId + "_" +fileName.substring(0, fileName.lastIndexOf(".")) + "_" + TimeUtil.getSecondTimestamp() + ".png");
                json.putByPath("picIfo", FileUtil.FILE_PATH+FileUtil.MCFF + issueId + "_" +fileName.substring(0, fileName.lastIndexOf(".")) + "_" + TimeUtil.getSecondTimestamp() + ".png");
                // 添加到数据库
                Mcff newMcff = JSONUtil.toBean((JSONObject) json, Mcff.class);
                newMcff.setIssueId(issueId);
                newMcff.setOriginFilename(fileName);
                newMcff.setSpectralIrregularity((BigDecimal)json.getByPath("spectral_Irregularity"));
                newMcff.setSpectralUneven((BigDecimal)json.getByPath("spectral_Uneven"));
                newMcff.setPictureUrl(FileUtil.FILE_PREFIX + (String) json.getByPath("picIfo"));
                mcffMapper.insert(newMcff);
//            int end = TimeUtil.getSecondTimestamp();
//            System.out.println(end-start);
                // 从缓存中移除
                mcffMap.get(issueId).remove(fileName);
                return newMcff;
            } catch (Exception e) {
                System.out.println(e.getMessage());
                throw new CustomException(ResultCode.PARAMETER_ERROR);
            }
        }
    }

    String getFilePath(Integer issueId, String fileName){
        Issue issue = issueMapper.getIssueMessageById(issueId);
        if(issue == null) {
            return "";
        }
        if(issue.getUrl()==null|| issue.getUrl().equals("")) {
            return "";
        } else {
            String[] urls = issue.getUrl().split("\\$");
            for (String url : urls) {
                String suffixName = url.substring(url.lastIndexOf("."));
                String name = url.substring(url.lastIndexOf("/") + 1);
                if (fileName.equals(name) && (suffixName.equals(".mp3") || suffixName.equals(".wav"))) {
                    return url;
                }
            }
            return "";
        }
    }
}




